package com.fsd.admin.quartz.schedule;

import javax.annotation.Resource;

import com.fsd.admin.service.*;
import com.fsd.admin.service.impl.Sys_SystemParametersServiceImpl;
import com.fsd.core.util.DateTimeUtil;
import com.fsd.core.wechat.entity.message.resp.TemplateMessage;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricProcessInstanceQuery;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import com.fsd.admin.model.A_Employee;
import com.fsd.admin.model.B_article;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 计划任务列表
 * @author Administrator
 *
 */
@Component
public class MyPrintSchedule{
	
	private static final Logger log = Logger.getLogger(MyPrintSchedule.class);
	
	@Resource(name = "sys_databackupServiceImpl")
	private Sys_DatabackupService databackupService;
	
	@Resource(name = "b_articleServiceImpl")
	private B_articleService articleService;

	@Autowired
	private A_EmployeeService employeeService;

	@Autowired
	private Sys_SystemParametersService sysParamService;

	@Autowired
	private E_pushtemplatesService pushtemplatesService;

	@Autowired
	private HistoryService historyService;

	@Autowired
	private RepositoryService repositoryService;

	@Autowired
	private RuntimeService runtimeService;

	@Autowired
	private TaskService taskService;

	@Autowired
	private Z_emailService emailService;
	
	/**
	 * 每日04时进行数据备份
	 */
	//@Scheduled(cron = "0 0 4 * * ?")
    public void ArticleHistory(){
		try {
			A_Employee employee = new A_Employee();
			databackupService.saveDatabackup(employee);   // 定时进行数据备份操作
			log.info("数据备份成功... ...");
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
		}
    }
	
	/**
	 * 每日08时进行上一日文章发布总量统计，并推送数据至微信
	 */
	//@Scheduled(cron = "0 0 8 * * ?")
    public void AccountArticle(){
		try {
			B_article article = new B_article();
			articleService.saveCountNumPerDay(article);
			log.info("文章统计成功... ...");	//统计前一日文章的发布量，并推送数据至微信
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
		}
    }

	@Scheduled(cron = "0 0/5 * * * ?")
	public void checkActivitiTimeout(){
		try{
			//流程定义列表
			List<ProcessDefinition> list = repositoryService.createProcessDefinitionQuery().list();
			for (ProcessDefinition processDefinition : list) {
				HistoricProcessInstanceQuery historicProcessInstanceQuery = historyService.createHistoricProcessInstanceQuery();
				// 设置查询条件
				historicProcessInstanceQuery.processDefinitionKey(processDefinition.getKey());
				//流程实例列表
				List<HistoricProcessInstance> processInstanceList = historicProcessInstanceQuery.list();
				for (HistoricProcessInstance historicProcessInstance : processInstanceList) {
					// 流程是否结束
					ProcessInstance pi = runtimeService.createProcessInstanceQuery().processInstanceId(historicProcessInstance.getId()).singleResult();
					if(pi != null){
						List<Task> taskList = taskService.createTaskQuery().processInstanceId(pi.getId()).list();
						Task nowTask = taskList.get(0);
						SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						System.out.println("任务当前节点：" + nowTask.getName());
						System.out.println("任务开始时间：" + formatter.format(nowTask.getCreateTime()));
						if(nowTask.getDueDate() != null){
							System.out.println("任务截止时间：" + formatter.format(nowTask.getDueDate()));
							int day = DateTimeUtil.differentDays(new Date(), nowTask.getDueDate());
							System.out.println("距到期还剩：" + day);
							if(day <= 5){
								//发送站内信和微信提醒
								String userId = nowTask.getAssignee();
								System.out.println("给这个人发送消息：" + userId);
								A_Employee employee = employeeService.get(userId);

								// 发送微信通知
								if(employee.getIswechatbind() != null && "true".equals(employee.getIswechatbind())){
									String wechatApiId = sysParamService.getParameterValueByCode(Sys_SystemParametersServiceImpl.WECHATMEMBER, employee.getCompanyid());
									TemplateMessage message = new TemplateMessage();
									message.setItem("first", "尊敬的" + employee.getRealname(), "#000000");
									message.setItem("keyword1", nowTask.getId(), "#000000");
									message.setItem("keyword2", processDefinition.getName() + "-" + nowTask.getName(), "#000000");
									message.setItem("keyword3", employee.getRealname(), "#000000");
									message.setItem("keyword4", formatter.format(nowTask.getDueDate()), "#000000");
									message.setItem("keyword5", "待办流程即将到期，请及时前往平台办理", "#000000");
									message.setItem("remark", "兰州工业学院创新创业学院", "#1111EE");
									pushtemplatesService.sendTemplateMessage(wechatApiId, "lccb", employee, message);
								}

								// 发送站内信通知
								StringBuffer sb = new StringBuffer();
								sb.append("任务类型：" + processDefinition.getName());
								sb.append("<br />");
								sb.append("任务名称：" + nowTask.getName());
								sb.append("<br />");
								sb.append("到期时间：" + formatter.format(nowTask.getDueDate()));
								sb.append("<br />");
								sb.append("请及时办理，以免逾期");
								sb.append("<br />");
								sb.append("兰州工业学院创新创业学院");
								emailService.saveMessage("您的待办任务即将超时，请及时处理。", sb.toString(), employee);
							}
						}
					}
				}
			}
		}catch (Exception e){
			e.printStackTrace();
		}
	}
}
